package com.itheima.test05;

import com.itheima.test03.Student;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

/*
题目五：
	1.把题目三中得到的Student.txt文件中的内容读取到程序中，并封装为Student对象放入ArrayList集合中
	2.在该过程中遇到的异常全部用try...catch...finally的方式处理
 */
public class Test05 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("D:\\IdeaProjects\\studentManagerSystem\\homework0917\\student.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
//        FileOutputStream fos = new FileOutputStream("D:\\IdeaProjects\\studentManagerSystem\\homework0917\\student.txt");
        ArrayList<Student> stuArraylist = new ArrayList<>();
        byte[] bytes = new byte[1024];
        int i;
        String s = "";
        try {
            while ((i=fis.read(bytes)) != -1){
                s = s + new String(bytes);
            }
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

//        System.out.println(s);
        String[] students = s.split("\n");
        for (String student : students) {
//            System.out.println(student);
            String[] attribute = student.split(",");
            String name = null;
            String gender = null;
            String age = null;
            String score = null;
            if (!("".equals(student.trim()))){
                for (int i1 = 0; i1 < attribute.length; i1++) {
                    if (attribute[i1].contains("name")){
                        name = attribute[i1].substring(7, attribute[i1].length() - 1);
                    }
                    if (attribute[i1].contains("gender")){
                        gender = attribute[i1].substring(8, attribute[i1].length() - 1);
                    }
                    if (attribute[i1].contains("age")){
                        age = attribute[i1].substring(4, attribute[i1].length() - 0);
                    }
                    if (attribute[i1].contains("score")){
                        score = attribute[i1].substring(6, attribute[i1].length() - 1);
                    }
                }
                Student student1 = new Student(name, gender, Integer.parseInt(age), Integer.parseInt(score));
                stuArraylist.add(student1);
            }
        }
        for (Student student : stuArraylist) {
            System.out.println("-------"+student);
        }
    }
}
